﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsService1
{
    /// <summary>
    /// 判断工位耗时变化
    /// </summary>
    public class StationDataComparer:IEqualityComparer<StationData>
    {
        private const float FloatEpsilon = 0.000001f; // 可以调整精度

        public bool Equals(StationData x, StationData y)
        {
            if (ReferenceEquals(x, y)) return true;
            if (x is null || y is null) return false;

            // 比较名称
            if (x.Name != y.Name) return false;

            // 比较主值
            if (x.MainValue is float xFloat && y.MainValue is float yFloat)
            {
                if (Math.Abs(xFloat - yFloat) > FloatEpsilon) return false;
            }
            else if (x.MainValue is double xDouble && y.MainValue is double yDouble)
            {
                if (Math.Abs(xDouble - yDouble) > FloatEpsilon) return false;
            }
            else if (!Equals(x.MainValue, y.MainValue))
            {
                return false;
            }

            // 比较时间戳（可以选择是否忽略毫秒）
            return Math.Abs((x.Timestamp - y.Timestamp).TotalMilliseconds) < 1;
        }

        public int GetHashCode(StationData obj)
        {
            if (obj is null) return 0;

            unchecked
            {
                int hash = 17;
                hash = hash * 23 + (obj.Name?.GetHashCode() ?? 0);

                // 对于浮点数，可以先转换为整数再计算哈希
                if (obj.MainValue is float f)
                {
                    hash = hash * 23 + ((int)(f * 1000000)).GetHashCode();
                }
                else
                {
                    hash = hash * 23 + (obj.MainValue?.GetHashCode() ?? 0);
                }

                hash = hash * 23 + obj.Timestamp.GetHashCode();
                return hash;
            }
        }
    }

    /// <summary>
    /// 判断时间戳变化
    /// </summary>
    public class StationDataComparer2 : IEqualityComparer<StationData>
    {
        public bool Equals(StationData x, StationData y)
        {
            if (ReferenceEquals(x, y)) return true;
            if (x is null || y is null) return false;

            // 只比较名称和时间戳
            if (x.Name != y.Name) return false;

            // 比较时间戳，检查是否完全相同
            return x.Timestamp == y.Timestamp;
        }

        public int GetHashCode(StationData obj)
        {
            if (obj is null) return 0;

            unchecked
            {
                int hash = 17;
                hash = hash * 23 + (obj.Name?.GetHashCode() ?? 0);
                hash = hash * 23 + obj.Timestamp.GetHashCode();
                return hash;
            }
        }
    }
}
